package com.hengxinguotong.zhihuichengjian.ui.material;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Material;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.PersonLiableListActivity;
import com.hengxinguotong.zhihuichengjian.ui.SearchPersonActivity;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 材料领用
 * Created by liux on 2017/3/20.
 */

public class MaterialUseActivity extends BaseActivity {

    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_test)
    HXTextView saveTest;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.name_tv)
    HXTextView nameTv;
    @BindView(R.id.model_tv)
    HXTextView modelTv;
    @BindView(R.id.unit_tv)
    HXTextView unitTv;
    @BindView(R.id.manufacturer_tv)
    HXTextView manufacturerTv;
    @BindView(R.id.count_canuse_tv)
    HXTextView countCanuseTv;
    @BindView(R.id.use_count_etv)
    HXEditTextView useCountEtv;
    @BindView(R.id.used_date_tv)
    HXTextView usedDateTv;
    @BindView(R.id.used_person_tv)
    HXTextView usedPersonTv;
    @BindView(R.id.tel_tv)
    HXTextView telTv;
    @BindView(R.id.company_tv)
    HXTextView companyTv;
    @BindView(R.id.remark_etv)
    HXEditTextView remarkEtv;
    @BindView(R.id.check_pass)
    RadioButton checkPass;
    @BindView(R.id.check_rectification)
    RadioButton checkRectification;
    @BindView(R.id.check_rg)
    RadioGroup checkRg;
    @BindView(R.id.check_ll)
    LinearLayout checkLl;
    private AlertDialog dialog;
    private int year = 0;
    private int monthOfYear = 0;
    private int dayOfMonth = 0;
    private final int SELECTMATERIAL = 10001;
    private final int SELECTPERSON = 10002;
    private Material selectMaterial;
    private User selectUser;
    private Material material;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_use);
        ButterKnife.bind(this);
        material = (Material) getIntent().getSerializableExtra("material");
        initView();
    }

    private void initView() {
        if (material != null) {
//            if (material.getStatus() == 1&&SPUtil.getString(this,"userId").equals(material.getAcquisitionId())) {
//                checkLl.setVisibility(View.VISIBLE);
//            } else {
            saveTest.setVisibility(View.GONE);
//            }
            Utils.setEditTextViewUnable(material.getName(), nameTv);
            Utils.setEditTextViewUnable(material.getModel(), modelTv);
            Utils.setEditTextViewUnable(material.getUnit(), unitTv);
            Utils.setEditTextViewUnable(material.getManufacturer(), manufacturerTv);
            Utils.setEditTextViewUnable(material.getAvailableQuantity(), countCanuseTv);
            Utils.setEditTextViewUnable(material.getQuantity() + "", useCountEtv);
            Utils.setEditTextViewUnable(material.getApproachDate(), usedDateTv);
            Utils.setEditTextViewUnable(material.getUsePerson(), usedPersonTv);
            Utils.setEditTextViewUnable(material.getMobile(), telTv);
            Utils.setEditTextViewUnable(material.getProjectCompanyName(), companyTv);
            Utils.setEditTextViewUnable(material.getRemark(), remarkEtv);

        } else {
            Calendar c = Calendar.getInstance();
            year = c.get(Calendar.YEAR);
            monthOfYear = c.get(Calendar.MONTH);
            dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
            usedDateTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
        }
    }

    private LinearLayoutManager getLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && data != null) {

        } else if (requestCode == SELECTMATERIAL && data != null) {
            selectMaterial = (Material) data.getSerializableExtra("material");
            modelTv.setText(selectMaterial.getModel());
            nameTv.setText(selectMaterial.getName());
            manufacturerTv.setText(selectMaterial.getManufacturer());
            countCanuseTv.setText(selectMaterial.getAvailableQuantity());
            unitTv.setText(selectMaterial.getUnit());
        } else if (requestCode == SELECTPERSON && data != null) {
            User selectUser = (User) data.getSerializableExtra("selectUser");
            usedPersonTv.setText(selectUser.getName());
            telTv.setText(selectUser.getMobile());
            companyTv.setText(selectUser.getProjectCompanyName());

        }
    }


    private boolean checkContent() {
        if (selectMaterial == null) {
            showToast("请选择材料");
            return false;
        }

        if (Utils.isEmpty(useCountEtv.getEditableText().toString())) {
            showToast("请填写领用数量");
            return false;
        }

        try {
            if (Float.parseFloat(useCountEtv.getEditableText().toString()) > Float.parseFloat(selectMaterial.getAvailableQuantity())) {
                showToast("领用数量不能大于可领数量");
                return false;
            }
        } catch (NumberFormatException e) {
            showToast("数量不合法");
            return false;
        }

        if (selectUser == null) {
            showToast("请选择领用人");
            return false;
        }

        return true;

    }


    private void useMaterial() {
        if(!checkContent()){
            return;
        }
        RequestParams params = new RequestParams();
        params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));
        params.addBodyParameter("approachId", selectMaterial.getApproachId());
        params.addBodyParameter("materialId", selectMaterial.getMaterialId());
        params.addBodyParameter("recipientsDate", year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
        params.addBodyParameter("quantity", useCountEtv.getEditableText().toString());
        params.addBodyParameter("personId", selectUser.getPersonId());
        params.addBodyParameter("remark", remarkEtv.getEditableText().toString());
//        for (int i = 0; i < minPaths.size(); i++) {
//            params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
//        }

        Utils.requestData(getResources().getString(R.string.loading), this, "/material/addAcquisition/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                showToast("提交成功");
                setResult(1);
                finish();
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void showWheelViewDialog() {
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        MaterialUseActivity.this.year = year;
                        MaterialUseActivity.this.monthOfYear = monthOfYear;
                        MaterialUseActivity.this.dayOfMonth = dayOfMonth;
                        usedDateTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                },
                year, monthOfYear, dayOfMonth).show();
    }

    @OnClick({R.id.iv_back, R.id.save_test, R.id.name_tv, R.id.used_date_tv, R.id.used_person_tv})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_test:
                if (material != null) {
                    useExamine();
                } else {
                    useMaterial();
                }
                break;
            case R.id.name_tv:
                intent = new Intent(this, MaterialCanUseListActivity.class);
                startActivityForResult(intent, SELECTMATERIAL);
                break;
            case R.id.used_date_tv:
                showWheelViewDialog();
                break;
            case R.id.used_person_tv:
                intent = new Intent(this, PersonLiableListActivity.class);
                intent.putExtra("type", 0);
                startActivityForResult(intent, SELECTPERSON);
                break;
        }
    }


    private void useExamine() {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("id", material.getAcquisitionId());
            jsonObject.put("quantity", material.getQuantity());
            if (checkRg.getCheckedRadioButtonId() == R.id.check_pass) {
                jsonObject.put("status", "4");

            } else if (checkRg.getCheckedRadioButtonId() == R.id.check_rectification) {
                jsonObject.put("status", "2");
            } else {
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Utils.requestData(getResources().getString(R.string.loading), this, "/material/updateUseMaterialStatus/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                showToast("修改成功");
                setResult(1);
                finish();
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

}
